import os
import sys

cur_path = os.path.dirname(os.path.abspath(__file__))
father_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

def is_win():
    return sys.platform == "win32"

def platform():
    return 'win32' if is_win() else 'mac'

if not is_win():
    import plistlib

def modify_version_file(file, target, version):
    print(file)
    vs = version.split('.');
    with open(file, 'r') as f:
        lines = f.readlines()
        lines[3] = '#define {0}_MAJOR '.format(target) + vs[0] + '\n'
        lines[4] = '#define {0}_MINOR '.format(target) + vs[1] + '\n'
        lines[5] = '#define {0}_PATCH '.format(target) + vs[2] + '\n'
        lines[6] = '#define {0}_BUILD '.format(target) + vs[3] + '\n'
    with open(file, 'w') as f:
        for data in lines:
            f.write(data)
        f.flush()
    return

def modify_plist(plist_path, version):
    print(plist_path)
    plist = {}
    with open(plist_path, 'rb') as f:
        plist = plistlib.load(f)
        # print(plist)
        plist["CFBundleShortVersionString"] = version
        old_ver = int(plist["CFBundleVersion"])
        plist["CFBundleVersion"] = str(old_ver + 1)
    with open(plist_path, 'wb') as f:
        plistlib.dump(plist, f)
    return

def modify_nisi_file(nisi_path, version):
    print(nisi_path)
    with open(nisi_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        lines[7] = '!define PRODUCT_VERSION \"{0}\"\n'.format(version)
        lines[46] = 'OutFile \"YingCe_{0}.exe\"\n'.format(version)
    with open(nisi_path, 'w', encoding='utf-8') as f:
        for data in lines:
            f.write(data)
        f.flush()
    return

if __name__ == '__main__':
    version = sys.argv[1]
    print(version)
    # yingce
    modify_version_file(os.path.join(cur_path, './../src/app/version.h'), 'YINGCE', version)
    if is_win():
        modify_nisi_file(os.path.join(cur_path, './win/YingCe.nsi'), version)
    else:
        modify_plist(os.path.join(cur_path, './../src/app/Info.plist'), version)